package com.xuan.common.security.service;


import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import com.xuan.common.core.constants.CacheConstants;
import com.xuan.common.core.constants.HttpConstants;
import com.xuan.common.core.constants.JwtConstants;
import com.xuan.common.core.domain.LoginUser;
import com.xuan.common.redis.service.RedisService;
import com.xuan.common.core.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@RefreshScope
public class TokenService {

    @Autowired
    private RedisService redisService;

    @Value("${jwt.secret}")
    private String secret;

    public String createToken(Long userId, String secret, Integer identity, String nickName, String headImage) {
        // 1. 生成用户唯一标识并设置到 token 载荷中
        String userKey = UUID.fastUUID().toString();
        Map<String, Object> map = new HashMap<>();
        map.put(JwtConstants.LONGIN_USER_ID, userId);
        map.put(JwtConstants.LOGIN_USER_KEY, userKey);
        String token = JwtUtils.createToken(map, secret);

        // 2. 将用户敏感信息存入到 redis 中
        String tokenKey = CacheConstants.LOGIN_TOKEN_KEY + userKey;
        LoginUser loginUser = new LoginUser();
        loginUser.setUserId(userId);
        loginUser.setIdentity(identity);
        loginUser.setNickName(nickName);
        loginUser.setHeadImage(headImage);
        // 设置用户的登录时间为 2 小时
        redisService.setCacheObject(tokenKey, loginUser, CacheConstants.EXP, TimeUnit.HOURS);
        return token;
    }


    public void extendToken(Claims claims) {
        String tokenKey = getTokenKey(claims);
        if (tokenKey == null) return;
        //
        Long expire = redisService.getExpire(tokenKey, TimeUnit.MINUTES);
        if (expire != null && expire > 0 && expire <= CacheConstants.REFRESH_TIME) {
            redisService.expire(tokenKey, CacheConstants.EXP, TimeUnit.HOURS);
        }
    }


    public LoginUser getUserInfo(String token, String secret) {
        Claims claims = getClaims(token, secret);
        String tokenKey = getTokenKey(claims);
        return redisService.getCacheObject(tokenKey, LoginUser.class);
    }


    public Long getUserId(Claims claims) {
        return claims == null ? null : claims.get(JwtConstants.LONGIN_USER_ID, Long.class);
    }


    public boolean removeToken(String token, String secret) {
        Claims claims = getClaims(token, secret);
        String tokenKey = getTokenKey(claims);
        if (tokenKey == null) return false;
        return redisService.deleteObject(tokenKey);
    }


    public void refreshLoginUser(String nickName, String headImage, String tokenKey) {
        LoginUser loginUser = redisService.getCacheObject(tokenKey, LoginUser.class);
        if (loginUser == null) return;
        loginUser.setNickName(nickName);
        loginUser.setHeadImage(headImage);
        redisService.setCacheObject(tokenKey, loginUser, CacheConstants.EXP, TimeUnit.HOURS);
    }

    /**
     *  解析 token 并获取存储到 redis 的 key
     * @param claims
     * @return  redis 的 key
     */
    public String getTokenKey(Claims claims) {
        if (claims == null) return null;

        String userKey = (String) claims.get(JwtConstants.LOGIN_USER_KEY);
        return CacheConstants.LOGIN_TOKEN_KEY + userKey;
    }

    public Claims getClaims(String token, String secret) {
        // 去除令牌前缀
        token = getToken(token);
        Claims claims = null;
        try {
            claims = JwtUtils.parseToken(token, secret);
            if (claims == null) {
                return null;
            }
        } catch (Exception e) {
            return null;
        }
        return claims;
    }


    /**
     *   若 token 存在前缀，则去除
     * @param token 令牌
     * @return  去除前缀的 token
     */
    private String getToken(String token) {
        if (token != null && token.startsWith(HttpConstants.PREFIX)) {
            token = token.replace(HttpConstants.PREFIX, StrUtil.EMPTY);
        }
        return token;
    }

}
